<template>
  <div class="content-table">
    <!-- <el-card> -->
    <!-- class="project-list-container" -->
    <div>
      <div class="list-h">
        <div>
          <el-button
            type="primary"
            @click="handleOpen"
            class="add-option"
            v-auth="`/system/manage--add`"
            >添加人员</el-button
          >
          <el-button
            v-if="isHidden"
            type="primary"
            class="add-option"
            @click="dialogVisibleTransferAdd = true"
            >账号激活</el-button
          >
        </div>
        <el-form
          :inline="true"
          class="demo-form-inline"
          :model="formInline"
          ref="formRef"
          @submit.prevent
        >
          <el-form-item label="姓名" prop="nameLike">
            <el-input
              v-model.trim="formInline.nameLike"
              clearable
              class="width-custom120"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
        <el-table
          :data="tableData"
          ref="tableRef"
          border
          v-adaptive="{ bottomOffset: 70 }"
          v-loading="loading"
          :height="300"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <template #empty>
            <el-empty :image-size="150" description="暂无数据"></el-empty>
          </template>
          <!-- <el-table-column prop="id" label="ID" width="50"></el-table-column> -->
          <el-table-column type="index" label="序号" width="50">
            <template v-slot="scope">
              <span>{{
                (formInline.pageNum - 1) * formInline.pageSize +
                scope.$index +
                1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="姓名"
            width="110"
          ></el-table-column>
          <el-table-column prop="userName" label="用户名"></el-table-column>
          <el-table-column
            prop="userType"
            label="用户类型"
            width="120"
            :formatter="formatterUserType"
          ></el-table-column>
          <el-table-column
            prop="roleName"
            label="角色"
            width="120"
          ></el-table-column>
          <!-- <el-table-column prop="nickName" label="昵称"></el-table-column> -->
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <!-- <el-table-column prop="address" label="地址"></el-table-column> -->
          <!-- <el-table-column prop="age" label="年龄"></el-table-column> -->
          <el-table-column
            prop="companyName"
            label="单位名称"
          ></el-table-column>
          <!-- <el-table-column prop="deviceId" label="设备ID"></el-table-column> -->
          <!-- <el-table-column prop="password" label="密码"></el-table-column> -->
          <el-table-column
            prop="phoneNum"
            label="手机号"
            width="100"
          ></el-table-column>
          <!-- <el-table-column prop="photo" label="头像"></el-table-column> -->

          <el-table-column prop="remark" label="备注"></el-table-column>

          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                title="确定重置该条密码吗？"
                @confirm="handleResetPassword(row)"
              >
                <template #reference>
                  <el-button type="text" v-auth="`/system/manage--delete`"
                    >重置密码</el-button
                  >
                </template>
              </el-popconfirm>
              <el-button
                type="text"
                @click="handleEdit(row)"
                v-auth="`/system/manage--edit`"
                >编辑</el-button
              >
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                title="确定删除该条记录吗？"
                @confirm="handleDelete(row)"
              >
                <template #reference>
                  <el-button type="text" v-auth="`/system/manage--delete`"
                    >删除</el-button
                  >
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-skeleton>
    </div>
    <re-pagination
      :total="total"
      v-show="total > 0"
      v-model:page="formInline.pageNum"
      v-model:limit="formInline.pageSize"
      @pagination="handleSearch"
    />
    <!-- </el-card> -->
    <el-dialog
      :title="mode === 'add' ? '添加人员' : '编辑人员'"
      v-model="dialogFormVisible"
      destroy-on-close
      width="600px"
    >
      <user-detail
        @emitClose="emitClose"
        :mode="mode"
        :userInfo="userInfo"
        :companyInfo="companyInfo"
      />
    </el-dialog>
    <el-dialog
      title="人员激活"
      v-model="dialogVisibleTransferAdd"
      width="920px"
    >
      <div style="margin-left: 54px">
        <el-radio-group v-model="actType">
          <el-radio label="1" size="large">普通权限</el-radio>
          <el-radio label="2" size="large">普通管理员</el-radio>
        </el-radio-group>
      </div>
      <add-user
        v-model:dialogVisibleTransferAdd="dialogVisibleTransferAdd"
        :currentUsers="acceptUsers"
        @emitAddUser="emitAddUser"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  reactive,
  toRefs,
  ref,
  inject,
  watch,
  defineComponent,
  nextTick,
  onMounted
} from "vue";
import { injectKeyCompany } from "./context";
import UserDetail from "./UserDetail.vue";
import RePagination from "/@/components/RePagination/index.vue";
// import { successMessage, warnMessage } from "/@/utils/message";
import NotifMessage from "/@/utils/message/notification";
import {
  getUserList,
  deleteUser,
  resetPassword,
  actUserAuth
} from "/@/api/user";
import { userTypeEnum, ModeType, FormInlineType, UserInfoType } from "../types";
import { useUserStoreHook } from "/@/store/modules/user";
import AddUser from "../../../projectsA/acceptance/arrival/components/dialog/AddUser.vue";
import { storageLocal } from "/@/utils/storage";
// /@/views/acceptance/arrival/components/dialog/AddUser.vue
export default defineComponent({
  name: "UserManage",
  components: {
    UserDetail,
    RePagination,
    AddUser
  },

  setup() {
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const tableRef = ref<HTMLTableElement | null>(null) as any;
    const activeCategory: any = ref(inject(injectKeyCompany));
    const userHook = useUserStoreHook();

    let loading = ref<boolean>(false);
    let mode = ref<ModeType>("add");
    let dialogFormVisible = ref<boolean>(false);
    let dialogVisibleTransferAdd = ref<boolean>(false);
    const isHidden = ref<boolean>(false);
    let total = ref<number>(0);
    let formInline = reactive<FormInlineType>({
      companyId: null,
      nameLike: "",
      pageNum: 1,
      pageSize: 20
    });
    let state = reactive({
      actType: "1",
      acceptUsers: [],
      tableData: [] as UserInfoType[],
      userInfo: {} as UserInfoType,
      companyInfo: {}
    });
    const emitAddUser = async user => {
      const { code, message } = await actUserAuth({
        actType: state.actType,
        actUserList: user.idList
      });
      if (code === 200) {
        dialogVisibleTransferAdd.value = false;
        NotifMessage.success(message);
      } else {
        // warnMessage(`${message}`);
        NotifMessage.error(message);
      }
      console.log(user);
    };

    // 请求表格数据
    async function getTableData(obj: object = {}) {
      // 真实请求待添加
      loading.value = true;
      try {
        const { code, data } = await getUserList(obj);
        if (code === 200) {
          state.tableData = data.list;
          total.value = data.rows;
        }
      } catch (err) {
        console.log(err);
      } finally {
        loading.value = false;
      }
    }
    // 打开添加人员弹窗
    const handleOpen = (): void => {
      dialogFormVisible.value = true;
      mode.value = "add";
      // console.log(activeCategory);
      // if (activeCategory.value.id) {
      state.companyInfo = activeCategory;
      // }
    };

    const emitClose = (isSubmit: boolean) => {
      dialogFormVisible.value = false;
      if (isSubmit) {
        formInline.pageNum = 1;
        getTableData(formInline);
      }
    };

    // 格式化用户类型
    const formatterUserType = row => {
      return userTypeEnum[row.userType - 1].label;
    };

    // 重置条件
    const handleReset = (): void => {
      formRef.value.resetFields();
    };

    // 根据条件进行搜索
    const handleSearch = (): void => {
      getTableData(formInline);
    };

    // 编辑用户
    const handleEdit = (row): void => {
      dialogFormVisible.value = true;
      mode.value = "edit";
      state.userInfo = row;
    };

    // 删除用户
    const handleDelete = async (item: any) => {
      try {
        const { code, message } = await deleteUser({ id: item.id });
        if (code === 200) {
          // successMessage(`${message}`);
          NotifMessage.success(message);
          getTableData(formInline);
        } else {
          // warnMessage(`${message}`);
          NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 重置密码
    const handleResetPassword = async (item: any) => {
      try {
        const { code, message } = await resetPassword({ id: item.id });
        if (code === 200) {
          NotifMessage.success(message);
          getTableData(formInline);
        } else {
          NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 监听左侧树的变化，发起请求
    watch(activeCategory, newVal => {
      if (newVal?.id) {
        formInline.companyId = newVal.id;
      } else {
        formInline.companyId = null;
      }
      getTableData(formInline);
    });

    watch(
      () => userHook.isHidden,
      () => {
        nextTick(() => {
          tableRef.value.doLayout();
        });
      }
    );
    onMounted(() => {
      isHidden.value =
        storageLocal.getItem("info")?.username === "admin" ? true : false;
    });

    // 请求数据
    getTableData(formInline);
    return {
      ...toRefs(state),
      isHidden,
      total,
      mode,
      tableRef,
      formRef,
      dialogFormVisible,
      loading,
      formInline,
      handleOpen,
      handleReset,
      handleSearch,
      handleEdit,
      handleDelete,
      emitClose,
      formatterUserType,
      handleResetPassword,
      dialogVisibleTransferAdd,
      emitAddUser
    };
  }
});
</script>
<style lang="scss" scoped>
.content-table {
  width: 100%;
  height: 100%;
  padding: 10px;
  border: 1px solid #e4e7ed;
}
.content-table :deep .el-card__body {
  height: 100%;
}

.content-table :deep .el-table__fixed-right-patch {
  background: #eef1f6;
}
</style>
